<template>
  <div class="page-body">
    <div>
      <van-list
        v-show="loading || total > 0"
        :offset="100"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <slot :list="list"></slot>
      </van-list>
    </div>
  </div>
</template>

<script>
import { List } from "vant";

export default {
  components: {
    [List.name]: List,
  },
  props: {
    asyncFn: {
      type: Function,
      default: () => Promise.resolve({ content: [], total: 0 }),
    },
  },
  data() {
    return {
      page: 1,
      size: 20,
      total: 0,
      List: [],
      finished: false,
      loading: true,
      refreshing: false,
    };
  },
  methods: {
    onLoad() {
      this.LoadMove();
    },

    /**
     * @p {content} 返回的数组数据
     * @p {total} 总条数
     * **/
    async LoadMove() {
      if (this.refreshing) {
        this.List = [];
        this.refreshing = false;
      }
      await this.shell(300);
      return this.asyncFn(this.page, this.size)
        .then((res) => {
          if (!res) {
            return;
          }
          const { content = [], total = 0 } = res;
          this.List = this.List.concat(content);
          this.total = total;
          this.page += 1;
          this.loading = false;

          // 如果总条数小于等于数组长度 或者数组为空就停止加载
          if (this.total <= this.List.length || content.length === 0) {
            this.finished = true;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },

    reMove() {
      this.finished = false;
      this.loading = true;
      this.list = [];
      this.page = 1;
    },

    // 调用刷新方法
    refresh() {
      this.reMove();
      this.LoadMove();
    },
    shell(time) {
      return new Promise((resolve, rej) => {
        setTimeout(() => {
          resolve();
        }, time);
      });
    },
  },
};
</script>

<style scoped>
.page-body {
  height: 100%;
}
::v-deep .vant-list {
  height: auto;
}
</style>
